const app = angular.module("myApp",['ui.bootstrap', 'ui.bootstrap.treeview2','ui.select2']);
// const app = angular.module("myApp",['ui.bootstrap']);

const treeViewTemplate = `
<tree-view ng-if="graphTree != null && graphTree.g != null" tree-service="graphTree" node-label="text"></tree-view>
`;

app.controller("manageController",['$scope','$compile','$filter','$uibModal',function($scope,$compile,$filter,$uibModal){
    $scope.query={
        fault:FaultNode.faults[0]
    };

    $scope.faultModules=[];
    $scope.freeNodes = [];

    $scope.component_ref=null;

    $scope.toJSON = function (val) {
        return angular.toJson(val,true);
    };

    // $scope.faults=FaultNode.faults;
    FaultNode.loadFaults.callbacks.push(()=>{
        $scope.faults=FaultNode.faults;
        $scope.$apply();
    });
    FaultNode.loadFaults.callbacks.push(()=>{
        $scope.query.fault=FaultNode.faults[0];
        $scope.$apply();
    });
    FaultNode.loadFaults();

    $scope.components=ComponentNode.components;
    ComponentNode.loadComponents.callbacks.push(()=>$scope.components=ComponentNode.components);
    ComponentNode.loadComponents();

    // $scope.graphTree = new TreeView();
    $scope.graphTree = new NodeTreeView();
    $scope.$watch('query',function () {
        console.info($scope.query);
        if($scope.query.fault)
            Graph.loadGraph($scope.query.fault.id,function (g) {
                $scope.$apply(()=> {
                    // angular.element("#nodeDetail2").html("");
                    angular.element("#treeDiv").html("");
                    delete $scope.graph;
                    delete $scope.graphTree;
                    $scope.graph = g;
                    // g.markFreedomNode();
                    $scope.freeNodes = g.getRoot().$freelist;

                    $scope.graphTree = new NodeTreeView();
                    $scope.graphTree.g = g;
                    $scope.graphTree.collapseAll();
                    console.info($scope.graphTree);

                    let tp = $compile( treeViewTemplate )( $scope );
                    angular.element("#treeDiv").html("").append( tp );
                });
            });
    },true);

    // $scope.$watch('graphTree.selectedNode',function () {
    //     let node = $scope.graphTree.selectedNode;
        // if($scope.graph && !!node){
        //     let template = node.getTemplate($scope.graphTree.fromEdge,$scope.graph);
        //     let tp = $compile( template )( $scope );
        //     angular.element("#nodeDetail2").html("").append( tp );
        // }
    // },true);

    $scope.filterOfFault = function (fault) {
        if($scope.query.faultType && $scope.query.faultType!= ''){
            if(fault.faultCategory != $scope.query.faultType){
                return false;
            }
        }
        if($scope.query.faultModule && $scope.query.faultModule!= ''){
            if(fault.faultModule != $scope.query.faultModule){
                return false;
            }
        }
        return true;
    };

    $scope.refreshModules = function () {
        getCache("fault_module",val=>{
            $scope.faultModules=val.map(x=>{
                if(x.indexOf(':')<0){
                    return {
                        category:'',
                        name:x,
                    }
                }
                let arr = x.split(':',2);
                return ({
                    category:arr[0],
                    name:arr[1],
                })
            });
            $scope.faultModules.splice(0,0,'');
        },(callback,cache,name)=>{
            getConfigure('module',data=>{
                cache[name]={
                    lastTimestamp:new Date().getTime(),
                    value:data
                };
                callback(data);
            });
        },5000);
    };
    $scope.refreshModules();

    $scope.featureChoice = [];
    $scope.reasonChoice = [];
    $scope.featFaultResult = 0;
    $scope.featResult = [];
    $scope.featResult2 = [];
    $scope.initSamples = function(){
      //初始化数据集
        $.get('http://127.0.0.1:8080/init/'+$scope.query.fault.id,function (data) {
           console.info("模型初始化为：",data);
        });
    };

    $scope.featFeature = function(){
        let feat = 0;
        for (let i=0;i<$scope.featureChoice.length;i++) {
            feat += ($scope.featureChoice[i]||0)*(1<<i);
        }
        $.get('http://127.0.0.1:8080/feat/'+$scope.query.fault.id+'?feature='+feat,function (data) {
            console.info("模型匹配结果为：",data);
            $scope.featResult = data;
            $scope.$apply();
        });
    };

    $scope.trainFeature = function(){
        let feat = 0;
        let traint = 0;
        for (let i=0;i<$scope.featureChoice.length;i++) {
            feat += ($scope.featureChoice[i]||0)*(1<<i);
        }
        for (let i=0;i<$scope.reasonChoice.length;i++) {
            traint += ($scope.reasonChoice[i]||0)*(1<<i);
        }
        $.get('http://127.0.0.1:8080/train/'+$scope.query.fault.id+'?feature='+feat+'&reason='+traint,function (data) {
            console.info("模型更新为：",data);
            $.get('http://127.0.0.1:8080/feat/'+$scope.query.fault.id+'?feature='+feat,function (data) {
                console.info("新模型匹配结果为：",data);
                $scope.featResult2 = data;
                $scope.$apply();
            });
        });

    };


    $scope.persistGraph = function () {
        $scope.graph.persist(r=>alert("数据库同步成功！"),e=>console.error(e));
    };

    $scope.sortByOutId = function (f) {
        if(!f.outId){
            return 0;
        }
        return parseInt(f.outId,10);
    };

    // $scope.sortByEdgeId = function (edge) {
    //     return edge.id;
    // };

    $scope.nextFaults = function () {
        let currentFaults = $filter('filter')($scope.faults,{faultCategory:$scope.query.faultType});
        let currentOrdered = $filter('orderBy')(currentFaults,$scope.sortByOutId);
        let index = currentOrdered.indexOf($scope.query.fault);
        if(index<currentOrdered.length-1)
            $scope.query.fault = currentOrdered[index+1];
    };

    $scope.exportFaultAsJson = function () {
        const modalInstance = $uibModal.open({
            template: `<div>${angular.toJson($scope.graph.toJson())}</div>`,
            animation: true,
            size: 'lg'
        });
        // 更新页面内容
        // modalInstance.result.then(function(response) {
            // refreshByCloseStatus(response, $scope.vehicles);
        // });
    };
}]);
